<?php

/**
 * This is the model class for table "Pricing".
 *
 * The followings are the available columns in table 'Pricing':
 * @property integer $PricingIndex
 * @property string $OrderName
 * @property string $Type
 * @property double $AmountUS
 * @property string $Date
 * @property string $PM
 * @property string $CreateTime
 * @property string $UpdateTime
 * @property string $Note
 * @property string $Description
 * @property double $PUintPrice
 * @property integer $PQuantity
 * @property string $BuySell
 * @property string $Inventory
 * @property string $ProductName
 * @property integer $ShipmentQuantity
 * @property double $UnitPriceRMB
 * @property double $ExchangeRate
 * @property string $VendorCode
 * @property string $ProductModel
 * @property string $Mode
 * @property integer $ProductID
 * @property double $LAAvgCost
 * @property string $BS
 * @property string $PS
 * @property string $Series
 * @property string $Package
 * @property string $Status
 * @property string $Label
 * @property integer $Balance
 * @property string $Currency
 * @property string $ReceiptNo
 * @property string $PurchaseBy
 * @property string $Destination1
 * @property string $Destination2
 * @property string $Destination3
 * @property string $ToWhom
 * @property string $ProductLink
 * @property string $Inspector
 * @property string $InspectWay
 * @property string $InspectDate
 * @property string $TakePictures
 * @property string $Office
 * @property string $Division
 * @property string $SubDiv
 * @property string $Modifier
 * @property string $AccountingDiv
 * @property string $Buyer
 * @property string $Event
 * @property string $ProductDetail
 * @property string $BoxNum
 * @property string $ToLAMethod
 * @property integer $ToLAQty
 * @property string $CarrierNumber
 * @property string $OEFeedback
 * @property string $OEComment
 *
 * The followings are the available model relations:
 * @property OMS $orderName
 */
class Pricing extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Pricing the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'Pricing';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('Status, PQuantity, UnitPriceRMB, Buyer, ToLAQty', 'required'),
            array('PQuantity, ShipmentQuantity, ProductID, Balance, ToLAQty', 'numerical', 'integerOnly' => true),
            array('AmountUS, PUintPrice, UnitPriceRMB, ExchangeRate, LAAvgCost', 'numerical'),
            array('OrderName, ProductModel, BS, PS, Package, Status, Label, Currency, ReceiptNo, PurchaseBy, Destination1, Destination2, Destination3, ToWhom, Inspector, InspectWay, InspectDate, TakePictures, Office, Division, SubDiv, Modifier, AccountingDiv, Buyer, Event, BoxNum, ToLAMethod', 'length', 'max' => 50),
            array('Type, BuySell, Inventory, ProductName, VendorCode, Mode', 'length', 'max' => 100),
            array('Date, PM, CreateTime, UpdateTime, Series', 'length', 'max' => 20),
            array('Note, Description, OEFeedback, OEComment', 'length', 'max' => 1073741823),
            array('ProductLink, ProductDetail', 'length', 'max' => 200),
            array('CarrierNumber', 'length', 'max' => 80),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('PricingIndex, OrderName, Type, AmountUS, Date, PM, CreateTime, UpdateTime, Note, Description, PUintPrice, PQuantity, BuySell, Inventory, ProductName, ShipmentQuantity, UnitPriceRMB, ExchangeRate, VendorCode, ProductModel, Mode, ProductID, LAAvgCost, BS, PS, Series, Package, Status, Label, Balance, Currency, ReceiptNo, PurchaseBy, Destination1, Destination2, Destination3, ToWhom, ProductLink, Inspector, InspectWay, InspectDate, TakePictures, Office, Division, SubDiv, Modifier, AccountingDiv, Buyer, Event, ProductDetail, BoxNum, ToLAMethod, ToLAQty, CarrierNumber, OEFeedback, OEComment', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'orderName' => array(self::BELONGS_TO, 'OMS', 'OrderName'),
            'product' => array(self::BELONGS_TO, 'Product', 'ProductID'),
            'mids' => array(self::HAS_MANY, 'MidTab', 'PricingIndex', 'order' => 'mids.UpdateTime DESC'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'PricingIndex' => 'Pricing Index',
            'OrderName' => '订单编号',
            'Type' => 'Type',
            'AmountUS' => '总金额',
            'Date' => '采购日期',
            'PM' => 'Pm',
            'CreateTime' => '创建日期',
            'UpdateTime' => 'Update Time',
            'Note' => '验货提醒',
            'Description' => '内部提醒',
            'PUintPrice' => '单价(美元)',
            'PQuantity' => '订购数量',
            'BuySell' => 'Buy Sell',
            'Inventory' => 'Inventory',
            'ProductName' => '产品名称',
            'ShipmentQuantity' => '累积出货量',
            'UnitPriceRMB' => '单价(人民币)',
            'ExchangeRate' => 'Exchange Rate',
            'VendorCode' => 'Vendor Code',
            'ProductModel' => '产品编号',
            'Mode' => 'Mode',
            'ProductID' => 'Product',
            'LAAvgCost' => 'Laavg Cost',
            'BS' => 'Bs',
            'PS' => 'Ps',
            'Series' => 'Series',
            'Package' => 'Package',
            'Status' => '大货/样品',
            'Label' => 'Label',
            'Balance' => '未处理数量',
            'Currency' => 'Currency',
            'ReceiptNo' => '收据编号',
            'PurchaseBy' => '购买方式',
            'Destination1' => '收件部门1',
            'Destination2' => '收件部门2',
            'Destination3' => '收件部门3',
            'ToWhom' => '产品去向',
            'ProductLink' => '产品链接',
            'Inspector' => '验货人',
            'InspectWay' => '验货方式',
            'InspectDate' => '验货日期',
            'TakePictures' => '是否拍照',
            'Office' => 'Office',
            'Division' => 'Division',
            'SubDiv' => 'Sub Div',
            'Modifier' => 'Modifier',
            'AccountingDiv' => '付款部门',
            'Buyer' => '购买人',
            'Event' => '验货状态',
            'ProductDetail' => '产品细节',
            'BoxNum' => 'ETA Date',
            'ToLAMethod' => '运输方式',
            'ToLAQty' => '总运出数量',
            'CarrierNumber' => '货柜编号<br>(快递单号)',
            'OEFeedback' => '验货反馈',
            'OEComment' => 'OE备注',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('PricingIndex', $this->PricingIndex);
        $criteria->compare('OrderName', $this->OrderName, true);
        $criteria->compare('Type', $this->Type, true);
        $criteria->compare('AmountUS', $this->AmountUS);
        $criteria->compare('Date', $this->Date, true);
        $criteria->compare('PM', $this->PM, true);
        $criteria->compare('CreateTime', $this->CreateTime, true);
        $criteria->compare('UpdateTime', $this->UpdateTime, true);
        $criteria->compare('Note', $this->Note, true);
        $criteria->compare('Description', $this->Description, true);
        $criteria->compare('PUintPrice', $this->PUintPrice);
        $criteria->compare('PQuantity', $this->PQuantity);
        $criteria->compare('BuySell', $this->BuySell, true);
        $criteria->compare('Inventory', $this->Inventory, true);
        $criteria->compare('ProductName', $this->ProductName, true);
        $criteria->compare('ShipmentQuantity', $this->ShipmentQuantity);
        $criteria->compare('UnitPriceRMB', $this->UnitPriceRMB);
        $criteria->compare('ExchangeRate', $this->ExchangeRate);
        $criteria->compare('VendorCode', $this->VendorCode, true);
        $criteria->compare('ProductModel', $this->ProductModel, true);
        $criteria->compare('Mode', $this->Mode, true);
        $criteria->compare('ProductID', $this->ProductID);
        $criteria->compare('LAAvgCost', $this->LAAvgCost);
        $criteria->compare('BS', $this->BS, true);
        $criteria->compare('PS', $this->PS, true);
        $criteria->compare('Series', $this->Series, true);
        $criteria->compare('Package', $this->Package, true);
        $criteria->compare('Status', $this->Status, true);
        $criteria->compare('Label', $this->Label, true);
        $criteria->compare('Balance', $this->Balance);
        $criteria->compare('Currency', $this->Currency, true);
        $criteria->compare('ReceiptNo', $this->ReceiptNo, true);
        $criteria->compare('PurchaseBy', $this->PurchaseBy, true);
        $criteria->compare('Destination1', $this->Destination1, true);
        $criteria->compare('Destination2', $this->Destination2, true);
        $criteria->compare('Destination3', $this->Destination3, true);
        $criteria->compare('ToWhom', $this->ToWhom, true);
        $criteria->compare('ProductLink', $this->ProductLink, true);
        $criteria->compare('Inspector', $this->Inspector, true);
        $criteria->compare('InspectWay', $this->InspectWay, true);
        $criteria->compare('InspectDate', $this->InspectDate, true);
        $criteria->compare('TakePictures', $this->TakePictures, true);
        $criteria->compare('Office', $this->Office, true);
        $criteria->compare('Division', $this->Division, true);
        $criteria->compare('SubDiv', $this->SubDiv, true);
        $criteria->compare('Modifier', $this->Modifier, true);
        $criteria->compare('AccountingDiv', $this->AccountingDiv, true);
        $criteria->compare('Buyer', $this->Buyer, true);
        $criteria->compare('Event', $this->Event, true);
        $criteria->compare('ProductDetail', $this->ProductDetail, true);
        $criteria->compare('BoxNum', $this->BoxNum, true);
        $criteria->compare('ToLAMethod', $this->ToLAMethod, true);
        $criteria->compare('ToLAQty', $this->ToLAQty);
        $criteria->compare('CarrierNumber', $this->CarrierNumber, true);
        $criteria->compare('OEFeedback', $this->OEFeedback, true);
        $criteria->compare('OEComment', $this->OEComment, true);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }
    
    protected function beforeSave() {
        if (parent::beforeSave()) {
            if ($this->isNewRecord) {
                $this->CreateTime = $this->UpdateTime = date('Ymd H:i');
                $this->Date = date('Ymd'); 
                if($this->ToWhom=='O2C'){
                    $this->OrderName = 'GAAA';
                } elseif ($this->ToWhom == 'O2CC') {
                    $this->OrderName = 'GBBB';
                } else {
                    $this->OrderName = 'GCCC';
                }
                $this->OrderName .= date('ym') . '01';
                $order = OMS::model()->find("OrderName='$this->OrderName'");
                if(!$order){
                    header("Content-Type:text/html;charset=utf-8");
                    echo '<script>alert("订单号：'.$this->OrderName.'，不存在，请先添加");window.location.href="'.Yii::app()->createUrl('psi/create').'"</script>';
                }
            }
            
            $this->UpdateTime = date('Ymd H:i');            

            //根据producID带相应的product数据入库
            $product = Product::model()->findByPk($this->ProductID);
            $this->Division = $product->Div;
            $this->SubDiv = $product->SubDiv;
            $this->VendorCode = $product->VendorCode;
            $this->Currency = $product->Currency;
            $this->LAAvgCost = $product->LAAvgCost;
            $this->Inventory = $product->Inventory;
            $this->Office = $product->Type;

            //计算Unit Price(US$)和SubTotal
            $rate = Helper::getRate();
            $this->PUintPrice = number_format($this->UnitPriceRMB / $rate, 2,'.','');
            $this->AmountUS = number_format($this->PUintPrice * $this->PQuantity, 2,'.','');

//            $this->OrderName = Helper::getOrderNumber();
        }
        return true;
    }

    protected function afterSave() {
        parent::afterSave();
        Helper::updateAvgCost($this->ProductID);
    }
    
    protected function afterDelete() {
        parent::afterDelete();
        Helper::updateAvgCost($this->ProductID);
    }

}